package com.smap.control;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.dom.client.Style.BorderStyle;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.smap.core.Map;

public class ToolBar extends Composite implements ClickHandler {
	Map map;
	Panel p1;
	Panel p2;
	List<Button> btns = new ArrayList<Button>();

	public ToolBar(Map map) {
		this.map = map;
		Panel panel = new VerticalPanel();
		initWidget(panel);
		this.setStyleName("ToolBar");
		p1 = new VerticalPanel();
		p2 = new VerticalPanel();
		panel.add(p1);
		panel.add(p2);
		this.getElement().getStyle().setZIndex(100000);
	}

	public void addBtn(String cmd, String label, boolean radio) {
		Button btn = createBtn(cmd, label);
		btns.add(btn);
		if (radio) {
			p1.add(btn);
		} else {
			p2.add(btn);
		}
	}

	private Button createBtn(String cmd, String label) {
		Button btn1 = new Button(label);
		btn1.setStylePrimaryName("map_btn");
		btn1.addStyleName(cmd);
		btn1.setTitle(cmd);
		btn1.setSize("30px", "30px");
		btn1.addClickHandler(this);
		btn1.getElement().getStyle().setOpacity(0.9);
		btn1.getElement().getStyle().setBorderWidth(0, Unit.PX);
		return btn1;
	}

	public void enable(String cmd) {
		for (Button btn : btns) {
			if (cmd.equals(getCmd(btn))) {
				btn.setEnabled(true);
			}
		}
	}

	public void disable(String cmd) {
		for (Button btn : btns) {
			if (cmd.equals(getCmd(btn))) {
				btn.setEnabled(false);
			}
		}
	}

	public void onClick(ClickEvent event) {
		Button btn = (Button) event.getSource();
		if (btn.getParent().equals(p1)){
			for (Button bt : btns) {
				bt.getElement().getStyle().setBorderWidth(0, Unit.PX);
			}
			btn.getElement().getStyle().setBorderStyle(BorderStyle.SOLID);
			btn.getElement().getStyle().setBorderColor("black");
			btn.getElement().getStyle().setBorderWidth(1, Unit.PX);
		}
		map.command(getCmd(btn));
	}

	private String getCmd(Button btn) {
		String cmd = btn.getStyleName();
		cmd = cmd.replaceAll("map_btn ", "");
		return cmd;
	}

}
